package com.guli.order.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guli.base.exception.GuliException;
import com.guli.order.entity.Order;
import com.guli.order.service.OrderService;
import com.guli.utils.JwtUtils;
import com.guli.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author ZhaoZhenyu
 * @since 2022-10-04
 */

//@CrossOrigin
@RestController
@RequestMapping("/order/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    // 创建订单 得到会员信息 根据courseId
    @PostMapping("createOrder/{courseId}")
    public R createOrder(@PathVariable String courseId, HttpServletRequest request) {
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberId)) throw new GuliException(20001, "未登录");
        String orderId = orderService.saveOrder(courseId,memberId);
        return R.ok().data("orderId", orderId);
    }

    // 根据订单id查订单
    @GetMapping("getOrder/{orderId}")
    public R get(@PathVariable String orderId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderId);
        Order order = orderService.getOne(wrapper);
        return R.ok().data("item", order);
    }

    // 更新支付状态
    @GetMapping("updateStatus/{orderId}")
    public R updateStatus(@PathVariable String orderId) {
        Order order = orderService.getOne(new QueryWrapper<Order>().eq("order_no",orderId));
        order.setStatus(1);
        boolean flag = orderService.updateById(order);
        if (flag){
            return R.ok();
        }else {
            return R.error().message("更改支付状态失败");
        }
    }

    /**
     * 查询支付状态
     * @param memberId
     * @param courseId
     * @return
     */
    @GetMapping("/isBuyCourse/{memberId}/{courseId}")
    public boolean isBuyCourse(@PathVariable String memberId, @PathVariable String courseId) {
        // 订单状态是1表示支付成功
        int count = orderService.count(new QueryWrapper<Order>().eq("member_id", memberId).eq("course_id", courseId).eq("status", 1));
        if(count>0) {
            return true;
        } else {
            return false;
        }
    }

}

